package util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

public class BaseDao {
    private static String driver;
    private static String url;
    private static String userName;
    private static String passWord;

    private static BaseDao baseDao = null;

    public BaseDao(){
        Properties properties = new Properties();
        InputStream in = BaseDao.class.getClassLoader().getResourceAsStream("db.properties");
        try {
            properties.load(in);
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            userName = properties.getProperty("userName");
            passWord = properties.getProperty("passWord");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static BaseDao getBaseDao(){
        if (baseDao==null){
            baseDao = new BaseDao();
        }
        return baseDao;
    }

    public static PreparedStatement getPs(String sql){
        getBaseDao();
        PreparedStatement Ps = null;
        try {
            Class.forName(driver);
            Connection connection = DriverManager.getConnection(url, userName, passWord);
             Ps = connection.prepareStatement(sql);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return Ps;
    }
    public static void close(AutoCloseable...ages){
        if (ages!=null){
            for (AutoCloseable age : ages) {
                if (age!=null){
                    try {
                        age.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
